<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img
          alt="logo"
          src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/dfdba5317c0c20ce20e64fac803d52bc.svg~tplv-49unhts6dw-image.image"
        />
        <a-typography-title
          :style="{ margin: 0, fontSize: '18px' }"
          :heading="5"
        >
          Vue Admin
        </a-typography-title>
        <icon-menu-fold
          v-if="appStore.device === 'mobile'"
          style="font-size: 22px; cursor: pointer"
          @click="toggleDrawerMenu"
        />
      </a-space>
    </div>
    <ul class="right-side">
      <li>
        <a-tooltip content="刷新">
          <a-button class="nav-btn" type="outline" :shape="'circle'" @click="refresh">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
        </a-tooltip>
      </li>
<!--      <li>
        <a-tooltip :content="$t('settings.search')">
          <a-button class="nav-btn" type="outline" :shape="'circle'">
            <template #icon>
              <icon-search />
            </template>
          </a-button>
        </a-tooltip>
      </li>-->
<!--      <li>
        <a-tooltip :content="$t('settings.language')">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setLanguageVisible"
          >
            <template #icon>
              <icon-language />
            </template>
          </a-button>
        </a-tooltip>
        <a-dropdown trigger="click" @select="changeLocale">
          <div ref="triggerBtn" class="trigger-btn"></div>
          <template #content>
            <a-doption
              v-for="item in locales"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-doption>
          </template>
        </a-dropdown>
      </li>-->
      <li>
        <a-tooltip
          :content="
            theme === 'light'
              ? $t('settings.navbar.theme.toDark')
              : $t('settings.navbar.theme.toLight')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="handleToggleTheme"
          >
            <template #icon>
              <icon-moon-fill v-if="theme === 'dark'" />
              <icon-sun-fill v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-tooltip :content="$t('settings.navbar.alerts')">
          <div class="message-box-trigger">
            <a-badge :max-count="10" :count="countUnreradmsg">
              <a-button
                class="nav-btn"
                type="outline"
                :shape="'circle'"
                @click="setMessageVisible"
              >
                <icon-notification />
              </a-button>
            </a-badge>
          </div>
        </a-tooltip>
<!--        <a-popover
          trigger="click"
          :arrow-style="{ display: 'none' }"
          :content-style="{ padding: 0, minWidth: '400px' }"
          content-class="message-popover"
        >
          <div ref="refBtn" class="ref-btn"></div>
          <template #content>
            <message-box />
          </template>
        </a-popover>-->
        <message-box ref="messageRef" />
      </li>
      <li>
        <a-tooltip
          :content="
            isFullscreen
              ? $t('settings.navbar.screen.toExit')
              : $t('settings.navbar.screen.toFull')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="toggleFullScreen"
          >
            <template #icon>
              <icon-fullscreen-exit v-if="isFullscreen" />
              <icon-fullscreen v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-tooltip :content="$t('settings.title')">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setVisible"
          >
            <template #icon>
              <icon-settings />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-dropdown trigger="hover">
          <div :style="{ marginRight: '8px', cursor: 'pointer' }">
            <a-avatar :size="32">
              <img :src="avatar" alt="avatar"/>
            </a-avatar>
            <a-typography-text style="margin-left: 6px; line-height: 32px">
              {{ adminStore.username }}
            </a-typography-text>
          </div>
          <template #content>
<!--            <a-doption>
              <a-space @click="switchRoles">
                <icon-tag />
                <span>
                  {{ $t('messageBox.switchRoles') }}
                </span>
              </a-space>
            </a-doption>-->
            <a-doption>
              <a-space @click="$router.push({ name: 'Profile' })">
                <icon-user />
                <span>个人中心</span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="resetPwd">
                <icon-unlock />
                <span>修改密码</span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export />
                <span>退出</span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>
  </div>
  <reset-password ref="resetPwdRef"/>
</template>

<script lang="ts" setup>
  import { computed, ref, inject } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { Notification } from '@arco-design/web-vue';
  import { useDark, useToggle, useFullscreen, useStorage } from '@vueuse/core';
  import { useAppStore, useAdminStore } from '@/store';
  import { LOCALE_OPTIONS } from '@/locale';
  import useLocale from '@/hooks/locale';
  import useAdmin from '@/hooks/admin';
  import { apiClearCache } from '@/api/common';
  import ResetPassword from '@/views/admin/components/reset-pwd.vue';
  import MessageBox from '../message-box/index.vue';

  const appStore = useAppStore();
  const adminStore = useAdminStore();
  const { logout } = useAdmin();
  const { changeLocale } = useLocale();
  const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();
  const locales = [...LOCALE_OPTIONS];
  const avatar = computed(() => {
    // return userStore.avatar;
    return adminStore.full_avatar;
  });
  const theme = computed(() => {
    return appStore.theme;
  });
  const isDark = useDark({
    selector: 'body',
    attribute: 'arco-theme',
    valueDark: 'dark',
    valueLight: 'light',
    storageKey: 'arco-theme',
    onChanged(dark: boolean) {
      // overridden default behavior
      appStore.toggleTheme(dark);
    },
  });
  const toggleTheme = useToggle(isDark);
  const handleToggleTheme = () => {
    toggleTheme();
  };
  // 配置
  const setVisible = () => {
    appStore.updateSettings({ globalSettings: true });
  };
  // const refBtn = ref();
  const triggerBtn = ref();
  const messageRef = ref();
  // 消息
  const setMessageVisible = () => {
    // const event = new MouseEvent('click', {
    //   view: window,
    //   bubbles: true,
    //   cancelable: true,
    // });
    // refBtn.value.dispatchEvent(event);
    messageRef.value.fetchData();
  };
  // 退出
  const handleLogout = () => {
    logout();
  };
  // 切换语言
  const setLanguageVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    triggerBtn.value.dispatchEvent(event);
  };
  // 切换角色
  const switchRoles = async () => {
    const res = await adminStore.switchRoles();
    Message.success(res as string);
  };
  // const toggleDrawerMenu = inject<any>('toggleDrawerMenu');
  const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;

  // 刷新
  const reload = inject<any>('reload');
  const refresh = () => {
    // 清除缓存
    apiClearCache().then(res => {
      // setTimeout(() => {
      //   window.location.reload();
      // }, 300);
      reload();
    }).catch(() => {
      reload();
    });
  };

  // 未读消息
  const countUnreradmsg = ref(useStorage('count_unreradmsg', 0));
  const messageConfig = useStorage('message-config', {
    isRead: false,
    num: countUnreradmsg.value,
  });
  const notifyInit = () => {
    if (countUnreradmsg.value > messageConfig.value.num) {
      Notification.info({
        id: 'message',
        content: '有未读消息，请注意查看',
        closable: true,
        duration: 5 * 1000,
      });
      messageConfig.value.isRead = true;
    }
    messageConfig.value.num = countUnreradmsg.value;
  };
  notifyInit();

  const resetPwdRef = ref();
  // 重置密码
  const resetPwd = () => {
    resetPwdRef.value.fetchData();
  };
</script>

<style scoped lang="less">
  .navbar {
    display: flex;
    justify-content: space-between;
    height: 100%;
    background-color: var(--color-bg-2);
    border-bottom: 1px solid var(--color-border);
  }

  .left-side {
    display: flex;
    align-items: center;
    padding-left: 20px;
  }

  .right-side {
    display: flex;
    padding-right: 20px;
    list-style: none;
    :deep(.locale-select) {
      border-radius: 20px;
    }
    li {
      display: flex;
      align-items: center;
      padding: 0 10px;
    }

    a {
      color: var(--color-text-1);
      text-decoration: none;
    }
    .nav-btn {
      border-color: rgb(var(--gray-2));
      color: rgb(var(--gray-8));
      font-size: 16px;
    }
    .trigger-btn,
    .ref-btn {
      position: absolute;
      bottom: 14px;
    }
    .trigger-btn {
      margin-left: 14px;
    }
  }
</style>

<style lang="less">
  .message-popover {
    .arco-popover-content {
      margin-top: 0;
    }
  }
</style>
